export const saveImage = {
  data() {
    return {
      canvasW: 375, // 设备宽
      maskHidden: false,
      imagePath: '', // 显示生成的图片
      mainPic: '',
      erPic: '',
      topPic: '',
      bottomPic: '',
      avatar: '',
      txt: '',
      width2: '',
      height2: ''
    }
  },
  mounted() {
    // 获取屏幕的宽度为画布宽
    let that = this
    uni.getSystemInfo({
      success(res) {
        let {
          windowWidth
        } = res
        that.canvasW = windowWidth
      }
    });
  },
  methods: {
    // 获取图片信息
    getImageInfo(image) {
      return new Promise((req, rej) => {
        uni.getImageInfo({
          src: image,
          success: function(res) {
            console.log(res)
            req(res)
          },
        });
      })
    },
    /*  canvas文本换行 */
    drawText(ctx, str, leftWidth, initHeight, titleHeight, canvasWidth) {
      let lineWidth = 0;
      let lastSubStrIndex = 0; //每次开始截取的字符串的索引
      for (let i = 0; i < str.length; i++) {
        lineWidth += ctx.measureText(str[i]).width;
        if (lineWidth > canvasWidth) {
          ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight); //绘制截取部分
          initHeight += 22; //22为 文字大小20 + 2
          lineWidth = 0;
          lastSubStrIndex = i;
          titleHeight += 22;
        }
        if (i == str.length - 1) { //绘制剩余部分
          ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
        }
      }
      // 标题border-bottom 线距顶部距离
      titleHeight = titleHeight + 10;
      return titleHeight;
    },

    getImgPromise(imgSrc) {
        let fun = function (resolve) {
            let canvas = document.createElement("canvas");//获取canvas对象
            let contex = canvas.getContext("2d"); //获取ctx上下文对象
            let img = new Image(); //创建img对象
            let radius;
            img.crossOrigin = "anonymous"; // anonymous/use-credentials 判断元素的跨域资源请求需不需要凭证标志
            img.onload = function () {
                // 设置图片中心点
                let center = {
                    x: img.width / 2,
                    y: img.height / 2,
                };
                let { width, height } = img;
                // 根据图片宽高设置裁剪圆形图片直径
                if (img.width > img.height) {
                    radius = height / 2;
                } else {
                    radius = width / 2;
                }
                //   计算圆的半径以及canvas宽高
                var diameter = radius * 2;
                canvas.width = diameter;
                canvas.height = diameter;
                contex.clearRect(0, 0, diameter, diameter);
                contex.save();
                contex.beginPath();
                contex.arc(radius, radius, radius, 0, 2 * Math.PI); //画出圆形
                contex.clip(); //裁剪上面的圆形
                contex.drawImage(
                    img,
                    center.x - radius,
                    center.y - radius,
                    diameter,
                    diameter,
                    0,
                    0,
                    diameter,
                    diameter
                ); // 在圆形上嵌入图片
                contex.restore(); // 还原状态
                resolve(canvas.toDataURL("image/png", 1)); //toDataURL 将图片转为base64编码
            };
            img.src = imgSrc;
        };
        let promise = new Promise(fun);
        return promise;
    },
    //将canvas转换为图片保存到本地，然后将图片路径传给image图片的src
    async createNewImg() {
      let that = this;
      const {mainPic, topPic, avatar, bottomPic, erPic} = this

      console.log(mainPic, topPic, avatar, bottomPic, erPic)
      
      // this.mainPic = await this.getImageInfo(this.mainPic)[0].path    // 处理图片
      // this.erPic = await this.getImageInfo(this.erPic)[0].path      // 处理图片
      // this.topPic = await this.getImageInfo(this.topPic)[0].path     // 处理图片
      // this.bottomPic = await this.getImageInfo(this.bottomPic)[0].path       // 处理图片
      this.mainPic = (await this.getImageInfo(this.mainPic)).path    // 处理图片
      
      this.topPic = (await this.getImageInfo(this.topPic)).path     // 处理图片
      this.bottomPic = (await this.getImageInfo(this.bottomPic)).path       // 处理图片
      this.avatar = (await this.getImageInfo(this.avatar)).path      // 处理图片

      // this.erPic = await this.getBase64ImageInfo(this.erPic)

      var context = uni.createCanvasContext('mycanvas');

      // context.setFillStyle("rgba(0,0,0,0)") // #F24077            // 背景颜色

      const cw = this.canvasW
      
      const bl =  cw / 750

      context.fillRect(0, 0, cw, 1550 / 750 * (cw)) //  667 绘制一个矩形作为背景矩形x坐标、y坐标、图片宽、高

      context.drawImage(this.mainPic, 0, 0, cw, 1360 / 750 * cw); // 262 349

  
      context.drawImage(this.topPic, 0, 0, cw, 58 / 750 * cw);

			// 绘制圆角矩形
			context.save();
			context.beginPath();
			context.arc(bl * 30 + 25, bl * 145 + 25, 25, 0, 2 * Math.PI); // 圆心坐标(100, 100)，半径为100
      context.setStrokeStyle('#333333')
      context.stroke()
			context.closePath();
			context.clip()
      //绘制图像
      context.drawImage(this.avatar, bl * 30, bl * 145, 50, 50);
			context.restore(); // 恢复之前保存的绘图上下文状态

      

      // 绘制圆角矩形
			context.save();
			context.beginPath();
			context.arc(cw / 750 * 6 + cw / 750  * 158 / 2 + 13, 1360 / 750 * cw + cw / 750  * 158 / 2 + 10,  cw / 750  * 158 / 2, 0, 2 * Math.PI); // 圆心坐标(100, 100)，半径为100
      context.setStrokeStyle('#333333')
      context.stroke()
			context.closePath();
			context.clip()
       //绘制右下角小程序二维码
      context.drawImage(this.erPic, cw / 750 * 6 + 13, 1360 / 750 * cw + 10, cw / 750  * 158, cw / 750  * 158);
			context.restore(); // 恢复之前保存的绘图上下文状态

      context.drawImage(this.bottomPic, 0, 1360 / 750 * cw, cw, cw / 750  * 197);

      context.setFontSize(26);
      // context.setFillStyle('#000'); // #FFF
      context.setTextAlign('left');
      if(this.txt.length>7) {
        this.txt = this.txt.slice(0,7)+ '...'
      }
      context.fillText(this.txt, bl * 130, bl * 175);
      context.stroke();

      //   context.setFontSize(15);
      //   context.setFillStyle('#333');
      //   context.setTextAlign('left');
      //   // context.fillText(todaySaying, 37, 480);
      //   this.drawText(context, todaySaying, 37, 470, 30, 300);   // 调用行文本换行函数（300则换行）
      //   context.stroke();

      context.draw();
      // });
      //将生成好的图片保存到本地
      setTimeout(function() {
        uni.canvasToTempFilePath({
          canvasId: 'mycanvas',
          success: function(res) {
            var tempFilePath = res.tempFilePath;
            that.imagePath = tempFilePath;
            that.canvasHidden = true
            that.baocun()
            console.log('将生成好的图片保存到本地', res, that.imagePath)
          },
          fail: function(res) {
            console.log(res);
          }
        }, that);
      }, 200);
    },
    getBase64ImageInfo (base64Data){
      const fs = wx.getFileSystemManager()
      let times = new Date().getTime()
      let codeImg = wx.env.USER_DATA_PATH + '/' + times + '.png'
      return new Promise((req, rej) => {
        fs.writeFile({
          filePath: codeImg,
          data: base64Data,
          encoding: 'base64',
          success: (res) => {
            console.log(res, codeImg)
            req(codeImg)
          },
          fail: (err)=> {
            console.log(err)
          }
        })
      })
    },
    //点击保存到相册
    baocun() {
      var that = this
      let {
        imagePath
      } = this
      console.log('点击保存到相册', imagePath)
      wx.showShareImageMenu({
        path: imagePath,
        success: ()=>{
        },
        fail: (res)=> {
            console.log(res)
            if( res.errMsg.indexOf('deny')!=-1||res.errMsg.indexOf('denied')!=-1 ){
              uni.showModal({
                title: '提示',
                content: '需要您授权保存相册',
                showCancel: false,
                success() {
                  uni.openSetting({
                    success(settingdata) {
                      if (settingdata.authSetting[
                        'scope.writePhotosAlbum']) { //是否授权保存到相册
                        wx.showModal({
                          title: '提示',
                          content: '获取权限成功,再次保存图片即可成功',
                          showCancel: false,
                        })
                      } else {
                        uni.showModal({
                          title: '提示',
                          content: '获取权限失败，无法保存到相册',
                          showCancel: false,
                        })
                      }
    
                    },
                  })
                },
                fail() {
                  uni.$u.toast('您已取消')
                },
              })
            }
        }
      })
      // uni.saveImageToPhotosAlbum({
      //   filePath: imagePath,
      //   success(res) {
      //     uni.showModal({
      //       content: '海报已保存到相册',
      //       showCancel: false,
      //       confirmText: '去分享',
      //       confirmColor: '#333',
      //       success: function(res) {
      //         if (res.confirm) {
      //           console.log('用户点击确定');
      //           wx.showShareImageMenu({
      //             path: imagePath
      //           })
      //           /* 该隐藏的隐藏 */
      //           that.maskHidden = false
      //         }
      //       },
      //       fail: function(res) {
      //         console.log(11111)
      //       }
      //     })
      //   },
      //   fail() {
      //     uni.showModal({
      //       title: '提示',
      //       content: '需要您授权保存相册',
      //       showCancel: false,
      //       success() {
      //         uni.openSetting({
      //           success(settingdata) {
      //             if (settingdata.authSetting[
      //               'scope.writePhotosAlbum']) { //是否授权保存到相册
      //               wx.showModal({
      //                 title: '提示',
      //                 content: '获取权限成功,再次保存图片即可成功',
      //                 showCancel: false,
      //               })
      //             } else {
      //               uni.showModal({
      //                 title: '提示',
      //                 content: '获取权限失败，无法保存到相册',
      //                 showCancel: false,
      //               })
      //             }

      //           },
      //         })
      //       },
      //       fail() {
      //         uni.$u.toast('您已取消')
      //       },
      //     })
      //   },

      // })
    },

    //点击生成
    formSubmit(e) {
      var that = this;
      this.maskHidden = false
      uni.showToast({
        title: '海报生成中...',
        icon: 'loading',
        duration: 1000
      });
      setTimeout(function() {
        uni.hideToast()
        that.createNewImg(); // 绘图
        that.maskHidden = true
      }, 1000)
    },
  }
}